//
//  CQViewController.m
//  CQVRPlayer
//
//  Created by chenchangqing on 06/20/2016.
//  Copyright (c) 2016 chenchangqing. All rights reserved.
//

#import "CQVRViewController.h"
#import "ZYInputAlertView.h"
#import <CQVRPlayer/VRPlayer.h>

#define screen_width [UIScreen mainScreen].bounds.size.width
#define screen_height [UIScreen mainScreen].bounds.size.height

@interface CQVRViewController ()<CQVRRenderViewDataSource,CQVideoControlViewDelegate>

@property (nonatomic, weak) IBOutlet CQVRRenderView *vrplayerView;
@property (nonatomic, weak) IBOutlet UILabel *linkL;// 连接地址
@property (nonatomic, weak) IBOutlet UIButton *linkBtn;// 链接播放按钮

@property (nonatomic, strong) NSArray *scenes;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *vrplayerViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *vrplayerViewTop;

@end

@implementation CQVRViewController

/// MARK: - Life cycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // vr渲染视图约束
    _vrplayerViewHeight.constant = screen_width * 9/16;
    _vrplayerViewTop.constant = 0;
    
    // 增加视频控制视图
    NSBundle *vrbundle = [NSBundle bundleWithPath:[[[NSBundle bundleForClass:self.class] bundlePath] stringByAppendingPathComponent:@"CQVRPlayer.bundle"]];
    CQVideoControlView *videoControlView = [vrbundle loadNibNamed:@"CQVideoControlView" owner:nil options:nil].firstObject;
    [videoControlView hideBack:YES];
    videoControlView.delegate = self;
    [_vrplayerView addSubview:videoControlView];
    _vrplayerView.videoControlView = videoControlView;
    _vrplayerView.isHorizontalScreenDirection = NO;
    
    // 约束
    videoControlView.translatesAutoresizingMaskIntoConstraints = NO;
    NSDictionary *views = NSDictionaryOfVariableBindings(videoControlView);
    
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[videoControlView]-0-|" options:0 metrics:nil views:views]];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[videoControlView]-0-|" options:0 metrics:nil views:views]];
    
    // 设置代理
    [self.vrplayerView setDataSource:self];
    
    // 准备场景
    [self prepareScenes];
    [_vrplayerView reloadData];
    
    // 注册通知监听者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
// 处理旋转过程中需要的操作

- (void)orientationChanged:(NSNotification *)note  {
    
    UIDeviceOrientation o = [[UIDevice currentDevice] orientation];
    switch (o) {
        case UIDeviceOrientationPortrait:            // Device oriented vertically, home button on the bottom
            break;
        case UIDeviceOrientationPortraitUpsideDown:  // Device oriented vertically, home button on the top
            break;
        case UIDeviceOrientationLandscapeLeft:      // Device oriented horizontally, home button on the right
            [self clickedFullScreen:nil];
            break;
        case UIDeviceOrientationLandscapeRight:      // Device oriented horizontally, home button on the left
            break;
        default:
            
            break;
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}

- (BOOL)shouldAutorotate{
    return NO;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"%s",__FUNCTION__);
}

/// MARK: - CQVideoControlViewDelegate

- (void)clickedBack:(id<CQVideoControlViewProtocol>)videoControlView {
    
    if (!self.vrplayerView.isHorizontalScreenDirection) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        
        [self clickedFullScreen:videoControlView];
    }
}

- (void)clickedFullScreen:(id<CQVideoControlViewProtocol>)videoControlView {
    
    CGFloat duration = [UIApplication sharedApplication].statusBarOrientationAnimationDuration;
    
    if (!self.vrplayerView.isHorizontalScreenDirection) {
        
        self.vrplayerView.isHorizontalScreenDirection = YES;
        
        _vrplayerViewHeight.constant = MIN(screen_width, screen_height);
        _vrplayerViewTop.constant = 0;
        
        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
        [UIView animateWithDuration:duration animations:^{
            self.view.transform = CGAffineTransformMakeRotation(M_PI*0.5);
            self.view.bounds = CGRectMake(0, 0, screen_width, screen_height);
        } completion:^(BOOL finished) {
        }];
        
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];
        _linkBtn.hidden = YES;
        [self.vrplayerView.videoControlView hideBack:NO];
        [self.vrplayerView.videoControlView hidePre:YES];
        [self.vrplayerView.videoControlView hideNext:YES];
        
    }else{
        
        self.vrplayerView.isHorizontalScreenDirection = NO;
        
        _vrplayerViewHeight.constant = MIN(screen_width, screen_height) * 9/16;
        _vrplayerViewTop.constant = 0;
        
        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:NO];
        [UIView animateWithDuration:duration animations:^{
            self.view.transform = CGAffineTransformIdentity;
            self.view.bounds = CGRectMake(0, 0, screen_width, screen_height);
        } completion:^(BOOL finished) {
        }];
        _linkBtn.hidden = NO;
        [self.vrplayerView.videoControlView hideBack:YES];
        [self.vrplayerView.videoControlView hidePre:YES];
        [self.vrplayerView.videoControlView hideNext:YES];
        
    }
}

- (IBAction)clickedLinkPlayBtn:(UIButton *)sender {
    __weak typeof(self) weakSelf = self;
    
    ZYInputAlertView *alertView = [ZYInputAlertView alertView];
    alertView.placeholder = @"请输入播放地址...";
    alertView.inputTextView.text = @"http://cache.utovr.com/2016012317521234402k/2016012317521234402k.m3u8";
    [alertView confirmBtnClickBlock:^(NSString *inputString) {
        weakSelf.linkL.text = inputString;
        
        CQVideoScene *currentScene = (CQVideoScene *)[weakSelf.scenes objectAtIndex:0];
        
        CQVideoPlayer *videoPlayer = [[CQVideoPlayer alloc]initWithURL:[NSURL URLWithString:inputString]];
        videoPlayer.videoTitle = nil;
        videoPlayer.vrRenderView = _vrplayerView;
        [currentScene.currentVideoPlayer free];
        currentScene.sceneVideoPlayer = videoPlayer;
        [currentScene.currentVideoPlayer play];
    }];
    [alertView show];
    
    // 打开按钮
    [[NSNotificationCenter defaultCenter] postNotificationName:UITextViewTextDidChangeNotification object:nil userInfo:nil];
}

- (void)prepareScenes {
    
    NSMutableArray *tscenes = [NSMutableArray arrayWithCapacity:0];
    /**
     场景零（远程-全景视频播放）
     */
    CQVideoScene *_scene0 = [[CQVideoScene alloc] init];
    [tscenes addObject:_scene0];
    
    _scenes = [NSArray arrayWithArray:tscenes];
}

#pragma mark - CQVRRenderViewDataSource

- (NSInteger)numberOfScenesInVRPlayer:(CQVRRenderView *)vrRenderView {
    
    return _scenes.count;
}

- (NSInteger)vrRenderView:(CQVRRenderView *)vrRenderView numberOfModelsInScene:(NSInteger)sceneIndex {
    
    CQScene *scene = [_scenes objectAtIndex:sceneIndex];
    NSMutableArray *models = scene.models;
    
    return models.count;
}

- (CQScene *)vrRenderView:(CQVRRenderView *)vrRenderView sceneAtIndex:(NSInteger)sceneIndex {
    
    return [_scenes objectAtIndex:sceneIndex];
}

- (CQModel *)vrRenderView:(CQVRRenderView *)vrRenderView modelForSceneAtIndex:(NSIndexPath *)indexPath {
    
    CQScene *scene = [_scenes objectAtIndex:indexPath.section];
    NSMutableArray *models = scene.models;
    
    return [models objectAtIndex:indexPath.row];
}

@end
